package com.cn.client;

import com.cn.common.MessageQueue;
import com.cn.common.TopicRouteData;
import org.apache.commons.lang3.StringUtils;

import java.text.SimpleDateFormat;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

public class TopicPublishInfo {

    private List<MessageQueue> messageQueues = new ArrayList<>();
    private volatile ThreadLocalIndex threadLocalIndex = new ThreadLocalIndex();
    private TopicRouteData topicRouteData;

    /**
     * @param brokerName （失效的节点名称，客户端在连接broker节点失败后，会记住该broker节点）
     * @return
     */
    public MessageQueue selectMessageQueue(String brokerName) {
        if (StringUtils.isNotEmpty(brokerName)) {
            return selectOneMessageQueue();
        } else {
            Integer index = this.threadLocalIndex.getAndIncrement();
            if (messageQueues.size() == 0) {
                return null;
            }
            for (int i = 0, size = messageQueues.size(); i < size; i++) {
                int pos = (index++) % size;
                if (pos < 0) pos = 0;
                MessageQueue messageQueue = messageQueues.get(pos);
                if (!messageQueue.getBrokerName().equals(brokerName)) {
                    return messageQueue;
                }
            }
            return selectOneMessageQueue();
        }
    }

    public MessageQueue selectOneMessageQueue() {
        Integer index = this.threadLocalIndex.getAndIncrement();
        int size = this.messageQueues.size();
        int pos = (index++) % size;
        if (pos < 0) pos = 0;
        return this.messageQueues.get(pos);
    }

    public ThreadLocalIndex getThreadLocalIndex() {
        return threadLocalIndex;
    }

    public List<MessageQueue> getMessageQueues() {
        return messageQueues;
    }

    public void setMessageQueues(List<MessageQueue> messageQueues) {
        this.messageQueues = messageQueues;
    }

    public TopicRouteData getTopicRouteData() {
        return topicRouteData;
    }

    public void setTopicRouteData(TopicRouteData topicRouteData) {
        this.topicRouteData = topicRouteData;
    }

    @Override
    public String toString() {
        return "TopicPublishInfo{" +
                "messageQueues=" + messageQueues +
                ", threadLocalIndex=" + threadLocalIndex +
                ", topicRouteData=" + topicRouteData +
                '}';
    }

    public static void main(String[] args) {
        Map<String, String> map = new HashMap<>();
        String a = map.putIfAbsent("a", "a");
        System.out.println(a);
        System.out.println(map);
        String d = map.putIfAbsent("a", "c");
        System.out.println(d);
        System.out.println(map);
    }

}
